﻿using Lk.WebTow.Common;
using Lk.WebTow.Extension;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Lk.WebTow.Authorize
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class AdminAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
    {
        public const string AdminAuthorizeAttributeScheme = "AdminAuthorizeAttributeScheme";

        public AdminAuthorizeAttribute()
        {
            this.AuthenticationSchemes = AdminAuthorizeAttributeScheme;
        }
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var authenticate = context.HttpContext.AuthenticateAsync(AdminAuthorizeAttribute.AdminAuthorizeAttributeScheme);
            authenticate.Wait();
            if (authenticate.Result.Succeeded || this.SkipAdminAuthorize(context.ActionDescriptor))
            {
                return;
            }
            var httpRequest = context.HttpContext.Request;

            if (httpRequest.IsAjaxRequest())
            {
                string msg = "未登录或登录超时，请重新登录";
                string retResult = "{\"status\":" + 1001 + ",\"msg\":\"" + msg + "\"}";
                string json = JsonHelper.ObjectToJSON(retResult);
                context.Result = new ContentResult() { Content = json };
                return;
            }
            else
            {
                string url = context.HttpContext.Content("~/admin/login");
                url = string.Concat(url, "?returnUrl=", httpRequest.Path);

                context.Result = new RedirectResult(url);
                return;
            }
        }

        /// <summary>
        /// 如果控制器类上有跳过检查SkipCheckLoginAttribute特性标签，则直接return true 
        /// </summary>
        public virtual bool SkipAdminAuthorize(ActionDescriptor actionDescriptor)
        {
            var skipAuthorize = actionDescriptor.FilterDescriptors.Where(a => a.Filter is SkipAdminAuthorizeAttribute).Any();
            return skipAuthorize;
        }

    }

   
    /// <summary>
    /// 如果控制器类上有SkipCheckLoginAttribute特性标签，则直接return 
    /// </summary>
    [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method,AllowMultiple =false,Inherited =true)]
    public sealed class SkipAdminAuthorizeAttribute : Attribute, IFilterMetadata
    {

    }
}
